package pers.qianyu.service.impl;

import org.apache.rocketmq.spring.core.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.messaging.*;
import org.springframework.messaging.support.*;
import org.springframework.stereotype.*;
import org.springframework.transaction.annotation.*;
import pers.qianyu.dao.*;
import pers.qianyu.domain.*;

import java.util.*;

@Service
public class OrderServiceImpl2 {
    @Autowired
    private TxLogDao txLogDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public void createOrderBefore(Order order) {
        String txId = UUID.randomUUID().toString();
        Message<Order> message = MessageBuilder.withPayload(order)
                .setHeader("txId", txId)
                .build();
        // 发送半事务消息
        rocketMQTemplate.sendMessageInTransaction("tx-topic-group", "tx-topic", message, order);
    }

    /**
     * 本地事务
     *
     * @param txId
     * @param order
     */
    @Transactional(rollbackFor = Exception.class)
    public void createOrder(String txId, Order order) {
        // 执行本地事务代码
        orderDao.save(order);
        // 记录日志到数据库，回查使用
        TxLog txLog = new TxLog();
        txLog.setTxId(txId);
        txLog.setContent("事务测试");
        txLog.setDate(new Date());
        txLogDao.save(txLog);
    }
}
